﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Configuration;

namespace com.hyrentals.common.image
{
    public class ImageDirectoryManager
    {
        private const int LAYERS = 1;
        private const int COUNT_PER_LAYER = 4096;
        private const int IMAGE_ID_LENGTH = 34;

        private const string ORIGINAL_DIR = "origin";
        private const string DEFAULT_DIR = "default";

        private static string _workingDirectory = ConfigurationManager.AppSettings["WorkingMountDir"];

        private static string FetchRelativeDirFromImageId(string imageId)
        {
            if (string.IsNullOrEmpty(imageId) || imageId.Length != IMAGE_ID_LENGTH)
            {
                throw new Exception("invalid image id");
            }
            return imageId.Substring(imageId.Length - 5, 3);
        }

        private static string FetchSourceFromImageId(string imageId)
        {
            if (string.IsNullOrEmpty(imageId) || imageId.Length != IMAGE_ID_LENGTH)
            {
                throw new Exception("invalid image id");
            }
            return imageId.Substring(imageId.Length - 2, 2);
        }

        public static void Init()
        {
            //Step1 先创建真正的工作目录，             
            //如果文件较多，可以有多个RealDirectory  
            //需要一定的映射算法，根据ID映射到不同的文件夹,
            if (!Directory.Exists(_workingDirectory))
            {
                Directory.CreateDirectory(_workingDirectory);
            }

            //step2 有4096*type种类个Real文件夹
            for (int i = 0; i < 0xfff; i++)
            {
                string dirName = i.ToString("x3");
                string subDir = Path.Combine(_workingDirectory, dirName);
                if (!Directory.Exists(subDir))
                {
                    Directory.CreateDirectory(subDir);
                }
            }
        }


        public static string GetOriginalImageDir(string imageId)
        {
            return GetImageDir(imageId, ImageCategoryEnum.Original);
        }

        public static string GetDefaultImageDir(string imageId)
        {
            return GetImageDir(imageId, ImageCategoryEnum.Default);
        }

        private static string GetImageDir(string imageId, ImageCategoryEnum category)
        {
            string relateiveDir = FetchRelativeDirFromImageId(imageId);
            string source = FetchSourceFromImageId(imageId);
            return Path.Combine(_workingDirectory, relateiveDir, source, ((byte)category).ToString("x2"));
        }

        public static byte[] GetImageFilePath(string imageId, string ext)
        {
            string imageDir = GetDefaultImageDir(imageId);
            string imageFilePath = Path.Combine(imageDir, imageId + ext);
            if (File.Exists(imageFilePath))
            {
                return File.ReadAllBytes(imageFilePath);
            }
            return null;

        }

    }
}
